// 注册路由的业务逻辑处理
const express = require("express");
const router = express.Router();
const usertable = require("../../database/userinfo")

router.post("/", async (req, res) => {
    let { username, password } = req.body;
    let userDoc = await usertable.findOne({ username })
    if (!userDoc) {
        res.send({
            code: 2,
            message: "用户未注册"
        })
        return
    } if (userDoc.password == password) {
        let userInfo = {
            _id: userDoc._id,
            username: userDoc.username,
            photo: userDoc.photo,
            admin: userDoc.admin,
        }
        req.session.userInfo = userInfo;
        res.send({
            code: 0,
            message: "登录成功",
            data: userInfo
        })
    } else {
        res.send({
            code: 3,
            message: "密码错误",
        })
    }

});

//检测是否登录
router.post("/isCheck", (req, res) => {
    let data = req.session.userInfo;
    //    console.log(data);
    if (data) {
        //已登录
        res.send({
            code: 0,
            msg: "已经登录",
            data
        })
    } else {
        //未登录
        res.send({
            code: 1,
            msg: "未登录",
            data: {}
        })
    }
});

//退出登录
router.post("/out", (req, res) => {
    req.session.destroy(); //销毁当前的session
    res.send({
        code: 0,
        message: "退出登录"
    })
});
module.exports = router;